package com.gitee.cheungming.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.cheungming.common.Result;
import com.gitee.cheungming.order.dao.OrderItemMapper;
import com.gitee.cheungming.order.dao.OrderMapper;
import com.gitee.cheungming.order.dto.OrderRequest;
import com.gitee.cheungming.order.feign.ConsumerClient;
import com.gitee.cheungming.order.feign.GoodsClient;
import com.gitee.cheungming.order.model.Order;
import com.gitee.cheungming.order.model.OrderItem;
import com.gitee.cheungming.order.service.IOrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author Zhang Ming
 * @since 2025-10-28
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Resource
    private OrderItemMapper orderItemMapper;

    @Resource
    private GoodsClient goodsClient;

    @Resource
    private ConsumerClient consumerClient;

    @Override
    @GlobalTransactional
    public Long createOrder(OrderRequest request) {
        // 诊断：检查A服务是否有XID
        String xid = RootContext.getXID();
        System.out.println("=== A服务调用前XID: " + xid + " ===");
        Order order = new Order();
        BeanUtil.copyProperties(request, order);
        order.setOrderNumber(new Snowflake().nextIdStr());
        order.setOrderStatus(Byte.parseByte("1"));
        save(order);
        List<OrderItem> goodsList = request.getGoodsList();
        consumerClient.payByScore(request.getConsumerId(), request.getTotalAmount().longValue());
        for (OrderItem orderItem : goodsList) {
            orderItem.setOrderId(order.getId());
            goodsClient.reduceStock(orderItem.getGoodsId(), orderItem.getGoodsCount());
        }

        orderItemMapper.insert(goodsList);
        return order.getId();
    }

    @Override
    public String testLoadBalance() {
        Result<?> result = goodsClient.testLoadBalance();
        System.out.println(JSONUtil.toJsonStr(result));
        if ("200".equals(result.getCode())) {
            return result.getData().toString();
        }
        return null;
    }
}
